package org.atlantis.sbe.server
import org.jboss.netty.bootstrap.ServerBootstrap
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory
import java.util.concurrent.Executors
import org.jboss.netty.channel.group.DefaultChannelGroup
import org.jboss.netty.channel.ChannelHandlerContext
import org.jboss.netty.channel.ExceptionEvent
import org.jboss.netty.channel.MessageEvent
import org.jboss.netty.channel.SimpleChannelUpstreamHandler
import org.jboss.netty.handler.codec.http.HttpRequest
import org.jboss.netty.handler.codec.http.QueryStringDecoder

import scala.collection.JavaConverters._

class NettyServer {

    val bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool,
        Executors.newCachedThreadPool))

    val allChannels = new DefaultChannelGroup
    
    class DefaultUpstreamHandler extends SimpleChannelUpstreamHandler {

        private def getHeaders(request: HttpRequest): Headers = {
            val headers: Map[String, Seq[String]] = request.getHeaderNames().asScala.map(key =>
                key.toUpperCase() -> request.getHeaders(key).asScala).toMap

            new Headers {
                def getAll(key: String) = headers.get(key.toUpperCase()).flatten.toSeq
                override def toString = headers.toString
            }
        }
        
        private def getCookies(request: HttpRequest): Cookies = {
            null
        }

        override def exceptionCaught(ctx: ChannelHandlerContext, e: ExceptionEvent) {
            e.getChannel.close
        }

        override def messageReceived(ctx: ChannelHandlerContext, e: MessageEvent) {
            allChannels add e.getChannel
            e.getMessage match {
                case httpRequest: HttpRequest =>
                    val keepAlive = httpRequest.isKeepAlive
                    val version = httpRequest.getProtocolVersion
                    val uri = new QueryStringDecoder(httpRequest.getUri())
                    val parameters = Map.empty[String, Seq[String]] ++ uri.getParameters.asScala.mapValues(_.asScala)
            }
        }
    }
}